﻿using LEE.EntityFrameworkCore.Extentions.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace LEE.EntityFrameworkCore.Extentions
{
    /// <summary>
    /// 软删除扩展
    /// </summary>
    public static class SoftDeleteExtension
    {
        public static ModelBuilder UseSoftDelete(this ModelBuilder modelBuilder)
        {
            /*
            * 软删除使用说明：
            * 1.在数据库实体中实现ISoftDelete接口,此处会通过反射方式分别添加过滤器；
            * 2.查询时会自动过滤已删除的数据；
            * 3.进行删除操作时，不做物理删除，只修改IsDeleted字段状态
            * 4.如果需要查询已删除的数据，需要在查询时使用“IgnoreQueryFilters()”方法，例如：_context.Users.Include(i => i.AuthInfo).IgnoreQueryFilters().AsNoTracking();
            */

            foreach (var entityType in modelBuilder.Model.GetEntityTypes().Where(e => typeof(ISoftDeleted).IsAssignableFrom(e.ClrType)))
            {
                modelBuilder.Entity(entityType.ClrType).Property<bool>("IsDeleted");
                var parameter = Expression.Parameter(entityType.ClrType, "e");
                var body = Expression.Equal(
                    Expression.Call(typeof(EF), nameof(EF.Property), new[] { typeof(bool) }, parameter, Expression.Constant("IsDeleted")), Expression.Constant(false));
                modelBuilder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter));
            }

            return modelBuilder;
        }
    }
}
